package com.education.business.correct;

import com.education.business.message.ExamMessage;
import com.education.business.message.QueueManager;
import com.education.business.message.RabbitMqConfig;
import com.education.business.service.education.OrgInfoService;
import com.education.business.service.education.StudentInfoService;
import com.education.business.service.education.SubjectInfoService;
import com.education.business.service.education.TestPaperInfoService;
import com.education.business.utils.CertUtil;
import com.education.common.constants.EnumConstants;
import com.education.common.constants.SystemConstants;
import com.education.common.context.TenantContext;
import com.education.common.utils.ObjectUtils;
import com.education.model.entity.*;
import com.education.model.request.StudentQuestionRequest;
import org.apache.shiro.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

/**
 * 试题管理员批改 (处理已作答主观题)
 * 教师后台批改试题暂时不考虑并发问题
 * @author zengjintao
 * @version 1.0
 * @create_at 2021/3/20 21:00
 */
public class TeacherQuestionCorrect extends QuestionCorrect {

    private int teacherMark = 0;

    private QueueManager queueManager;

    @Resource
    private StudentInfoService studentInfoService;
    @Resource
    private SubjectInfoService  subjectInfoService;
    @Resource
    private OrgInfoService orgInfoService;
    private TestPaperInfoService testPaperInfoService;

    public TeacherQuestionCorrect(StudentQuestionRequest studentQuestionRequest,
                                  ExamInfo examInfo, QueueManager queueManager,
                                  StudentInfoService studentInfoService,
                                  SubjectInfoService subjectInfoService,
                                  OrgInfoService orgInfoService,
                                  TestPaperInfoService testPaperInfoService,
                                  Map<Integer, String> questionAnswerInfo) {
        super(studentQuestionRequest, examInfo, questionAnswerInfo);
        this.queueManager = queueManager;
        this.studentInfoService = studentInfoService;
        this.subjectInfoService = subjectInfoService;
        this.orgInfoService = orgInfoService;
        this.testPaperInfoService = testPaperInfoService;
    }

    @Override
    public void correctStudentQuestion() {
        if (CollectionUtils.isEmpty(questionAnswerList)) {
            return;
        }
        questionAnswerList.forEach(questionAnswerItem -> {
            if (!isObjectiveQuestion(questionAnswerItem.getQuestionType()) &&
                    ObjectUtils.isNotEmpty(questionAnswerItem.getStudentAnswer())) {
                this.correctQuestionNumber++;
                StudentQuestionAnswer studentQuestionAnswer = createStudentQuestionAnswer(questionAnswerItem);
                studentQuestionAnswer.setMark(questionAnswerItem.getStudentMark());
                teacherMark += questionAnswerItem.getStudentMark();
                // 后台指定加入学员错题本
                if (questionAnswerItem.isErrorQuestionFlag()) {
                    this.addErrorNumber();
                    this.newStudentWrongBook(questionAnswerItem);
                    studentQuestionAnswer.setCorrectStatus(EnumConstants.CorrectStatus.ERROR.getValue());
                } else {
                    studentQuestionAnswer.setCorrectStatus(EnumConstants.CorrectStatus.CORRECTED.getValue());
                }
                super.addObjectiveQuestionAnswerList(studentQuestionAnswer);
                studentQuestionAnswerList.add(studentQuestionAnswer);
            }
        });
        // 生成证书
        StudentInfo studentInfo = studentInfoService.getById(studentQuestionAnswerList.get(0).getStudentId());
        int tenantId;
        try {
            tenantId = Integer.parseInt(studentInfo.getTenantId());
        } catch (Exception e) {
            throw new NumberFormatException(String.format("所属机构%s信息异常，无法完成批卷", studentInfo.getTenantId()));
        }
        OrgInfoEntity orgInfoEntity = orgInfoService.getById(tenantId);
        TestPaperInfo testPaperInfo = testPaperInfoService.getById(this.examInfo.getTestPaperInfoId());
        String cerUrl = null;
        if (null != testPaperInfo) {
            SubjectInfo subjectInfo = subjectInfoService.getById(testPaperInfo.getSubjectId());
            cerUrl = CertUtil.generateCert(subjectInfo.getName(), studentInfo, orgInfoEntity.getOrgName(), SystemConstants.EXAM_CER_LEVEL_PASS);
        }
        //  rabbitmq 发送考试提交消息
        ExamMessage examMessage = new ExamMessage();
        examMessage.setStudentQuestionAnswerList(studentQuestionAnswerList);
        examMessage.setStudentWrongBookList(getStudentWrongBookList());
        ExamInfo ei = getExamInfo();
        ei.setCerUrl(cerUrl);
        examMessage.setExamInfo(ei);
        examMessage.setRoutingKey(RabbitMqConfig.EXAM_QUEUE_ROUTING_KEY);
        examMessage.setExchange(RabbitMqConfig.EXAM_DIRECT_EXCHANGE);
        examMessage.setTenantId(TenantContext.getCurrentTenant());
        queueManager.sendQueueMessage(examMessage);
    }


    @Override
    public ExamInfo getExamInfo() {
        this.examInfo.setTeacherMark(teacherMark);
        this.examInfo.setCorrectFlag(EnumConstants.Flag.YES.getValue()); // 设置为已批改
        this.examInfo.setUpdateDate(new Date());
        this.examInfo.setErrorNumber(this.examInfo.getErrorNumber() + this.getErrorQuestionNumber());
        if (this.getQuestionNumber() == this.correctQuestionNumber) { //
            this.examInfo.setMark(teacherMark);
            this.examInfo.setCorrectType(EnumConstants.CorrectType.TEACHER.getValue());
        } else {
            this.examInfo.setMark(examInfo.getSystemMark() + teacherMark);
            this.examInfo.setCorrectType(EnumConstants.CorrectType.SYSTEM_AND_TEACHER.getValue());
        }
        this.sendStudentMessage(); // 发送批改完成消息通知
        return this.examInfo;
    }
}
